class String
  def words
    split(' ')
  end
end

def transfer(s)
  r = ""
  _trans(s) do
    |x|
    r += x
  end
  r
end


def dump(s)
  puts 'cvs chacl -R default:n'
  _trans(s) do
    |x|
    unless x.strip.empty?
      puts x
    end
  end
end

def _trans(s)
  empty_matcher = Proc.new {
    |x|
    ''
  }

  group = { }

  group_matcher = Proc.new {
    |x|
    if x =~ /(.+) = (.+)/
      group[$1] = $2.words
    end
    ''
  }

  matcher = empty_matcher
  s.each_line do
    |i|
    case i
    when /^#/ : 
    when /\[groups\]/ : matcher = group_matcher
    when /\[(.*)\]/ : matcher = new_dir_matcher(group, $1)
    else yield matcher.call(i)
    end
    yield ''
  end
end

def new_dir_matcher(group, dir)
  Proc.new {
    |i|
    if i =~ /(.+)(?: *)=(?: *)(.*)/
      gen(collect_group(group, $1.words), $2, dir)
    else
      ''
    end
  }
end

def collect_group(group, tokens)
  tokens.collect do
    |t|
    case t
    when /\*/ : group.values
    when /^@(.+)/ : group[$1]
    else t
    end
  end.flatten
end

def gen(c, rights, dir)
  (c.collect{ |x| chacl(x, rights, dir) }).join("\n")
end

class Stdin
  def each_line
    begin
      while true
        yield readline
      end
    rescue
    end
  end
end

def normalize_rights(right)
  if right.strip.empty?
    'n'
  else
    right
  end
end

def chacl(user, right, dir)
  "cvs chacl -R #{user}:#{normalize_rights(right)} #{dir}"
end


